// pages/seckillBuyNow/seckillBuyNow.js
const app = getApp();
import api from '../../../utils/util.js';
Page({

  /**
   * 页面的初始数据
   */
  data: {
    statusBarHeight: app.globalData.statusBarHeight,
    fullHeight: app.globalData.fullcontain,
    discount: app.globalData.discount,
    navmess: {
      navtitle: "购物车",
      backhide: 0,
      topheight: 1
    },
    count: 0, //合计
    number: 0, //件数
    allSelect: false,
    selectIds: [] //结算ids
  },
  pageto: function (e) {
    var url = e.currentTarget.dataset.url,
      data = e.currentTarget.dataset.datobj;
    app.goto(url, data);
  },
  // 减少
  bindMinus: function (e) {
    var index = parseInt(e.currentTarget.dataset.index),
      quantity = this.data.demolist[index].quantity,
      id = e.currentTarget.dataset.id;
    if (this.data.demolist[index].seckillId !== null) {
      var price = this.data.demolist[index].seckillPrice
    } else {
      var price = this.data.demolist[index].price
    }
    var demolist = this.data.demolist;
    if (demolist[index].selected && quantity > 0) {
      quantity--;
      this.setData({
        count: this.data.count - 1 * price,
        number: this.data.number - 1
      });
    } else if (quantity > 0) {
      quantity--;
    }
    demolist[index].quantity = quantity;
    this.setData({
      demolist: demolist
    });
    var params = {
      "token": this.data.token,
      "id": id,
      "quantity": quantity
    }
    api.post("/mini/my/cart/modifyCart", params).then(res => {
      if (res.code == 200) {

      }
    }).catch(res => {
      console.log("请求失败：", res);
      return false;
    })
  },
  // 增加
  bindPlus: function (e) {
    var index = parseInt(e.currentTarget.dataset.index),
      quantity = this.data.demolist[index].quantity,
      id = e.currentTarget.dataset.id;
    if (this.data.demolist[index].seckillId !== null) {
      var price = this.data.demolist[index].seckillPrice
    } else {
      var price = this.data.demolist[index].price
    }
    var demolist = this.data.demolist;
    if (demolist[index].selected) {
      quantity++;
      this.setData({
        count: this.data.count + 1 * price,
        number: this.data.number + 1
      });
    } else {
      quantity++;
    }
    demolist[index].quantity = quantity;
    this.setData({
      demolist: demolist
    });
    var params = {
      "token": this.data.token,
      "id": id,
      "quantity": quantity
    }
    api.post("/mini/my/cart/modifyCart", params).then(res => {
      if (res.code == 200) {

      }
    }).catch(res => {
      console.log("请求失败：", res);
      return false;
    })
  },
  // 勾选
  bindCheckbox: function (e) {
    var index = parseInt(e.currentTarget.dataset.index),
      selected = this.data.demolist[index].selected,
      quantity = parseInt(this.data.demolist[index].quantity),
      selectIds = this.data.selectIds;
    if (this.data.demolist[index].seckillId !== null) {
      var price = this.data.demolist[index].seckillPrice
    } else {
      var price = this.data.demolist[index].price
    }
    var demolist = this.data.demolist;
    demolist[index].selected = !selected;
    this.setData({
      demolist: demolist
    });
    if (!selected) {
      this.setData({
        count: this.data.count + quantity * price,
        number: this.data.number + quantity
      });
      // 需要结算的商品
      selectIds.push(e.currentTarget.dataset.id);
    } else {
      this.setData({
        count: this.data.count - quantity * price,
        number: this.data.number - quantity
      });
      for (var i = 0; i < selectIds.length; i++) {
        if (e.currentTarget.dataset.id == selectIds[i]) {
          selectIds.splice(i, 1)
        }
      }
    }
    console.log("勾选ids: ", selectIds);
    // 检测全选
    console.log("全选", this.checkisall())
    if (this.checkisall()) {
      this.setData({
        allSelect: true
      })
    } else {
      this.setData({
        allSelect: false
      })
    }
  },
  // 全选
  bindSelectAll: function () {
    var that = this;
    that.setData({
      allSelect: !that.data.allSelect
    })
    var demolist = that.data.demolist,
      count, number,
      selectIds = [];

    if (that.data.allSelect) {
      count = 0;
      number = 0;
      for (var i = 0; i < demolist.length; i++) {
        var quantity = parseInt(demolist[i].quantity);
        if (demolist[i].seckillId !== null) {
          var price = demolist[i].seckillPrice
        } else {
          var price = demolist[i].price
        }
        if (!demolist[i].selected) {
          demolist[i].selected = true;
        }
        number += quantity;
        count += quantity * price;
      }
      // 需要结算的商品
      for (var i = 0; i < demolist.length; i++) {
        selectIds.push(demolist[i].id);
      }
    } else {
      count = 0;
      number = 0;
      for (var i = 0; i < demolist.length; i++) {
        if (demolist[i].selected) {
          demolist[i].selected = false;
        }
      }
      selectIds = []
    }
    that.setData({
      demolist: demolist,
      count: count,
      number: number,
      selectIds: selectIds
    })
    console.log(selectIds)
  },
  // 检测全选功能
  checkisall: function () {
    var demolist = this.data.demolist,
      res = true;
    for (var i = 0; i < demolist.length; i++) {
      if (!demolist[i].selected) {
        res = false;
      }
    }
    return res
  },

  //手指触摸动作开始 记录起点X坐标
  touchstart: function (e) {
    //开始触摸时 重置所有删除
    let data = app.touch._touchstart(e, this.data.demolist)
    this.setData({
      demolist: data
    })
  },
  //滑动事件处理
  touchmove: function (e) {
    let data = app.touch._touchmove(e, this.data.demolist)
    this.setData({
      demolist: data
    })
  },
  //删除
  del: function (e) {
    var that = this,
      index = parseInt(e.currentTarget.dataset.index),
      id = e.currentTarget.dataset.id,
      selected = this.data.demolist[index].selected,
      quantity = parseInt(this.data.demolist[index].quantity);
    if (this.data.demolist[index].seckillId !== null) {
      var price = this.data.demolist[index].seckillPrice
    } else {
      var price = this.data.demolist[index].price
    }
    wx.showModal({
      title: '提示',
      content: '确认要删除此条信息么？',
      success: function (res) {
        if (res.confirm) {
          console.log('用户点击确定')
          var params = {
            "token": that.data.token,
            "id": id
          }
          api.post("/mini/my/cart/delCart", params).then(res => {
            if (res.code == 200) {
              that.data.demolist.splice(e.currentTarget.dataset.index, 1)
              if(selected){
                that.setData({
                  demolist: that.data.demolist,
                  count: that.data.count - quantity * price,
                  number: that.data.number - quantity
                })
              }else{
                that.setData({
                  demolist: that.data.demolist
                })
              }
            }
          }).catch(res => {
            console.log("请求失败：", res);
            return false;
          })
        } else if (res.cancel) {
          console.log('用户点击取消')
        }
      }
    })

  },
  // 结算传参
  settle: function () {
    var notNone = false,
      demolist = this.data.demolist;
    for (var i = 0; i < demolist.length; i++) {
      if (demolist[i].selected) {
        notNone = true
      }
    }
    if (!notNone) {
      wx.showToast({
        title: '请选择结算商品',
        icon: 'none',
        duration: 1500
      })
    } else {
      wx.navigateTo({
        url: "../checkOrderInfo/checkOrderInfo" + "?selectIds=" + JSON.stringify(this.data.selectIds.join(',')) + "&type=" + this.data.type,
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this;
    console.log("结算类型", options.type);
    this.setData({
      type: options.type
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    var that = this;
    var token = wx.getStorageSync('token');
    that.setData({
      token: token,
      allSelect: false,
      count: 0,
      number: 0,
      selectIds: []
    })
    api.post("/mini/my/cart/cart", {
      "token": token
    }).then(res => {
      if (res.code == 200) {
        console.log(res)
        that.setData({
          demolist: res.result.cartList
        })
      }
    }).catch(res => {
      console.log("请求失败：", res);
      return false;
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareappMessage: function () {

  }
})